import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from "@nestjs/common";
import { Request, Response } from 'express';

// 全局异常过滤器
@Catch()
export class ErroFilter implements ExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        console.log("错误",exception)
        const ctx = host.switchToHttp();
        const request = ctx.getRequest<Request>();
        const response = ctx.getResponse<Response>();

        // 检查是否为 HttpException，否则默认为 500 错误
        const status = exception instanceof HttpException ? exception.getStatus() : 500;
        // 捕获 SyntaxError，处理语法错误
        let errorMessage = exception.message;
        if (exception instanceof SyntaxError && exception.stack.includes('JSON')) {
            errorMessage = '请求中包含无效的 JSON 格式';
        } else if (exception.getResponse) {
            // 处理 HttpException 的 getResponse 方法
            const errors = exception.getResponse();
            errorMessage = errors['message'] || exception.message;
        }

        response.status(status).json({
            code: -1,
            time: Date.now(),
            status,
            message: errorMessage,
            path: request.url,
            requestId: request['requestId'],
        });
    }
}
